<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <coment-box v-on:func="loadComments"></coment-box>
        <ul class="list-group">
            <li class="list-group-item" v-for="item in list" :key="item.user">
                <span class="badge">评论人：{{item.user}}</span>
                {{item.content}}
            </li>
        </ul>
        
    </div>

    <template id="tmpl">
        <div>
            <div class="form-group">
                <label>评论人：</label>
                <input type="text" class="form-control" v-model="user"/>
            </div>
            <div class="form-group">
                <label>评论内容：</label>
                <textarea class="form-control" v-model="content"></textarea>
            </div>
            <div class="form-group">
                <input type="button" class="btn btn-primary" value="发表评论" @click="postComment">
            </div>
        </div>
    </template>

    <script>

        var comentBox = {
            data: function(){
                return {
                    user: '',
                    content: ''
                }
            }, 
            methods: {
                postComment() {
                    var comment = {id:Date.now(), user:this.user, content:this.content};
                    // 调用本地缓存，如果有就返回数组，否则返回一个空数组
                    var list = JSON.parse(localStorage.getItem('cmts') || '[]');
                    // 把对象加入到数组中
                    list.push(comment);
                    // 再把数组重新写入到本地缓存中
                    localStorage.setItem('cmts', JSON.stringify(list));
                    this.user = this.content = '';

                    this.$emit('func');
                }
            },
            template: '#tmpl'
        }

        var vm = new Vue({
            el: '#app',
            data: {
                list: [
                    {id:Date.now(), user: '李白', content: '天生我才必有用'},
                    {id:Date.now(), user: '江小白', content: '劝君更尽一杯酒'},
                    {id:Date.now(), user: '小马', content: '我姓马，风吹草低见牛羊的马'}
                ]
            }, 
            methods: {
                loadComments(){
                    // 从本
                    var list = JSON.parse(localStorage.getItem('cmts') || '[]');
                    this.list = list;
                }
            },
            components: {
                comentBox:comentBox
            },
            beforeCreate(){

            },
            created(){
                this.loadComments();
            }
        });
    </script>
</body>
</html>